<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes
        :horizontal="this.$store.getters.device === 'mobile'"
        class="default-theme"
      >
        <template v-if="!showEditor">
          <pane size="16">
            <el-col>
              <div class="head-container">
                <el-input
                  v-model="fileName"
                  placeholder="请输入文件夹名称"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px"
                />
              </div>
              <div class="head-container">
                <el-tree
                  ref="tree"
                  highlight-current
                  @node-expand="handleExpand"
                  @node-collapse="handleCollapse"
                  :data="folderTree"
                  :props="{
                    label: 'name',
                    children: 'children',
                  }"
                  node-key="id"
                  @node-click="handleNodeClick"
                >
                  <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <img
                        src="@/assets/images/leftF.png"
                        class="folder-icon"
                        style="width: 18px; margin-right: 5px"
                      />
                      <span>{{ node.label }}</span>
                    </span>
                  </template>
                </el-tree>
              </div>
            </el-col>
          </pane>
          <!--组件传递-->
          <pane size="84">
            <el-col>
              <div class="file-list-container">
                <FileList
                  @preview-event="handleFileOpens"
                  @folder-change="handleFolderChange"
                  @update-filelist="handleFilelistUpdate"
                  @edit-event="handleFileOpen"
                  :selectedNode="queryParams"
                  @refresh-event="handleQuery"
                  :folderTree="folderTree"
                  :fileList="currentFiles"
                  @selectFloder="handleNodeClick"
                  @refresh-tree="handleTreeRefresh"
                />
              </div>
            </el-col>
          </pane>
        </template>

        <template v-else>
          <pane size="100" style="height: 900px">
            <Detail :file="selectedFile" @close="handleEditorClose" />
          </pane>
        </template>
      </splitpanes>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { getFolderTrees } from "@/api/zhishiku/folder";
import FileList from "./filesystem/filelist.vue";
import Detail from "@/components/Detail";
import { EventBus } from "@/main";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect, Splitpanes, Pane, FileList, Detail },
  data() {
    return {
      folderTree: [],
      currentFiles: [], // 当前显示的文件列表

      treeProps: {
        label: "name",
        children: "children",
        isLeaf: (data) => !data.children || data.children.length === 0,
      },

      showEditor: false, //控制编辑器的显示状态
      selectedFile: null, // 当前选中的文件

      fileList: [],
      fileName: "",
      hoverIndex: -1,
      cardSpan: 4, // 初始每行展示5个卡片 (24 / 5 = 4.8，取整为4)
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        parentId: undefined,
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    fileName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.loadFolderTree();

    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });

    // 事件监听必须使用完全相同的事件名称
    EventBus.$on("open-template-editor", (templateData) => {
      console.log("[User] 接收到文件对象:", templateData);

      // 确保数据正确且包含必要字段
      if (!templateData.filePath || !templateData.id) {
        this.$message.error("文件数据不完整");
        return;
      }

      this.selectedFile = templateData;
      this.showEditor = true;
    });
  },
  mounted() {
    // window.addEventListener("wheel", this.handleWheel);
  },
  beforeDestroy() {
    // window.removeEventListener("wheel", this.handleWheel);
    EventBus.$off("open-template-preview");
  },
  methods: {
    // handleOpenTemplateEditor(template) {
    //   console.log("打开模板编辑器", template);
    //   this.selectedFile = template;
    //   this.showEditor = true;
    // },

    handleTreeRefresh() {
      console.log("刷新树形组件");
      this.loadFolderTree();
    },

    handleExpand(data) {
      data._icon = "el-icon-folder-opened"; // 展开状态图标
    },
    handleCollapse(data) {
      data._icon = "el-icon-folder"; // 折叠状态图标
    },

    loadFolderTree() {
      getFolderTrees().then((res) => {
        // 过滤文件节点（处理嵌套结构）
        const filterFolders = (nodes) => {
          return nodes.filter((node) => {
            if (node.type === "folder") {
              if (node.children) {
                node.children = filterFolders(node.children); // 递归过滤子节点
              }
              return true;
            }
            return false;
          });
        };
        this.folderTree = filterFolders(res.data);
      });
    },

    handleFilelistUpdate(newList) {
      this.currentFiles = [...newList]; // 必须创建新引用
    },
    handleFolderChange(payload) {
      console.log("收到文件夹切换事件", payload.id);
      this.queryParams.parentId = payload.id;
      this.handleQuery(); // 触发文件列表刷新
    },
    //关闭Editor
    handleEditorClose() {
      this.showEditor = false;
      this.selectedFile = null;
      // this.getList(); // 刷新文件列表
    },
    // 打开文件
    handleFileOpen(file) {
      this.selectedFile = file;
      this.showEditor = true;
    },
    handleFileOpens(file) {
      try {
        console.log("触发预览事件:", file);
        this.showEditor = false;
        this.$nextTick(() => {
          this.selectedFile = { ...file }; // 确保响应式更新
          this.showEditor = true;
        });
      } catch (e) {
        console.error("预览事件处理异常:", e);
      }
    },

    /**
     * 调整文件展示格式
     */
    // handleWheel(event) {
    //   if (event.deltaY < 0) {
    //     // 向上滚动，放大卡片
    //     this.cardSpan = Math.max(2, this.cardSpan - 1);
    //   } else {
    //     // 向下滚动，缩小卡片
    //     this.cardSpan = Math.min(8, this.cardSpan + 1);
    //   }
    // },
    getCardClass(type) {
      return {
        "folder-card": type === "folder",
        "file-card": type === "file",
        "video-card": type === "video",
        "image-card": type === "image",
      };
    },
    getFileIcon(type) {
      return {
        "el-icon-folder": type === "folder",
        "el-icon-document": type === "file",
        "el-icon-video-camera": type === "video",
        "el-icon-picture": type === "image",
      };
    },

    // 节点单击事件
    async handleNodeClick(nodeData) {
      try {
        this.queryParams.parentId = nodeData.id;

        const token = getToken();
        const res = await this.$axios.get(
          `${process.env.VUE_APP_BASE_API}/api/folder/${nodeData.id}/contents`,
          { headers: { Authorization: `Bearer ${token}` } }
        );

        // 状态码和数据结构校验
        if (res.status === 200 && res.data.code === 200) {
          const { childFolders = [], files = [] } = res.data.data || {};

          // 处理文件夹数据
          const folders = childFolders.map((f) => ({
            id: f.id,
            parentId: f.parentId,
            label: f.name,
            type: "folder",
            security: f.security,
            children: f.children || [],
          }));

          // 处理文件数据
          const filesData = files.map((f) => ({
            id: f.id,
            label: f.name,
            type: "file",
            security: f.security,
            currentVersion: f.currentVersion,
            filePath: f.filePath, // 文件路径
          }));
          console.log("filesData", filesData);

          // 响应式更新
          this.$nextTick(() => {
            this.currentFiles = [...folders, ...filesData];
          });
        } else {
          this.$message.error(res.data.message || "请求失败");
        }

        // 高亮当前选中节点
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(nodeData.id);
        });
      } catch (error) {
        if (error.response) {
          console.error("错误详情：", error.response.data);
          this.$message.error(`加载失败：${error.response.data.message}`);
        } else {
          this.$message.error("网络连接异常");
        }
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      if (this.$refs.tree && this.$refs.tree.getCurrentNode()) {
        const currentNode = this.$refs.tree.getCurrentNode();
        this.handleNodeClick(currentNode);
      }
      // 如果没有选中节点，刷新根目录
      else if (this.folderTree.length > 0) {
        this.handleNodeClick(this.folderTree[0]);
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.parentId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },

    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style scoped>
.file-list-container {
  min-height: 0px;
  max-height: 100%;
  width: fit-content;
  min-width: 800px;
  overflow: hidden;
}

.el-card {
  transition: all 0.3s ease;
}

.folder-card {
  background-color: #f0f9eb;
}

.file-card {
  background-color: #f4f4f5;
}

.video-card {
  background-color: #f0f4ff;
}

.image-card {
  background-color: #fff6f6;
}

.file-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
}

.file-content i {
  font-size: 40px;
  margin-bottom: 10px;
}

::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: rgba(64, 158, 255, 0.2) !important;
  color: #409eff !important;
}
</style>
